<script setup lang="ts">
import { ref, defineProps, defineEmits, withDefaults, watch, onMounted, toRaw } from "vue";
import { ElMessage } from "element-plus";
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
import { getDeviceByIdApi, updateDeviceApi } from '@/api/products/device';
import { useLogic } from "@/views/system/user/logic/logic";
import {getDeviceGroupOptionsApi} from "@/api/products/deviceGroup";
import { getProductOptionsApi } from "@/api/products/product";
import { handleTree } from "@/utils/tree";
import { getNetworkTypeOptions, getProductOpenStatusOptions } from "@/utils/appCommon/appCommonOptions/products";
import UploadImg from "@/views/components/uploads/uploadImg.vue";
import {getDeviceOptionsApi} from "@/api/products/device";
// 定义props
const props = withDefaults(defineProps<{
 visible: boolean;
 device: any;
}>(), { visible: false, device: null });

// 产品选项数据
const productOptions = ref([]);
const deviceGroupOptions = ref([]);
const {deptTreeList,getDeptTree}  = useLogic()
const networkTypeOptions = ref([]);
const parentDeviceList = ref([]);
// 设备类型选项
const deviceTypeOptions = [
  { val: 0, label: t('products.productPage.directDevice') },
  { val: 1, label: t('products.productPage.gatewayDevice') },
  { val: 2, label: t('products.productPage.subDevice') }
];
onMounted(async () => {
  await getDeptTree()
  const productOptionsRes = await getProductOptionsApi()
  if(productOptionsRes.code == 0){
    productOptions.value = [
      ...productOptionsRes.data.options.map(option => ({
        val: option.val,
        label: option.label
      }))
    ];
  }
  const deviceGroupOptionsRes = await getDeviceGroupOptionsApi()
  if(deviceGroupOptionsRes.code == 0){
    deviceGroupOptions.value = handleTree(deviceGroupOptionsRes.data.options);
    console.log(toRaw(deviceGroupOptions.value))
  }
  networkTypeOptions.value = await getNetworkTypeOptions()
})

// 本地对话框状态
const dialogVisible = ref(props.visible);

// 同步props到本地状态
watch(() => props.visible, (newVal) => { dialogVisible.value = newVal; }, { immediate: true });

// 通知父组件状态变化
watch(dialogVisible, (newVal) => { emit('update:visible', newVal); });

// 定义emits
const emit = defineEmits<{
 (e: 'update:visible', value: boolean): void;
 (e: 'close'): void;
 (e: 'success'): void;
}>();

// 表单数据 - 更新为小驼峰命名
const formData = ref<{
  id: number;
  deviceNo: string;
  name: string;
  channelNo: string;
  productId: number;
  deptId: number;
  groupId: number | null;
  type: number;
  remark: string;
  lng: number | null;
  lat: number | null;
  address: string;
  image: string;
  openStatus: number;
  parentId: number | null;
  networkType: 1 | 2;
}>({
  id: 0,
  deviceNo: '',
  name: '',
  channelNo: '',
  productId: 0,
  deptId: 0,
  groupId: null,
  type: 0,
  remark: '',
  lng: null,
  lat: null,
  address: '',
  image: '',
  openStatus: 0,
  parentId: null,
  networkType: 1,
});

// 监听设备数据变化 - 调用详情API
watch(
  () => props.device,
  async (newVal) => {
    if (newVal && newVal.id) {
      try {
        const response = await getDeviceByIdApi(newVal.id);
        if (response.code === 0) {
          formData.value = { ...response.data.info };
        } else {
          ElMessage.error(response.message || t('products.devicePage.getDetailFailed'));
        }
      } catch (error) {
        ElMessage.error(t('products.devicePage.getDetailFailed'));
        console.error('Failed to get device details:', error);
      }
    }
  },
  { immediate: true }
);

// 监听设备类型或部门ID变化，当类型为子设备时获取网关设备列表
watch([() => formData.value.type, () => formData.value.deptId], async () => {
  if (formData.value.type === 2 && formData.value.deptId) {
    try {
      const res = await getDeviceOptionsApi({
        type: "1", // 网关设备类型为1 为了避免直连类型0的误导，使用字符串
        deptId: formData.value.deptId,
        fieldKey: 'id',
        fieldLabel: 'name'
      });
      if (res.code === 0) {
        parentDeviceList.value = res.data.options || [];
      } else {
        parentDeviceList.value = [];
        ElMessage.error(res.msg || '获取网关设备失败');
      }
    } catch (error) {
      parentDeviceList.value = [];
      ElMessage.error('获取网关设备失败');
    }
  } else {
    parentDeviceList.value = [];
  }
}, { immediate: true });

// 提交表单 - 调用更新API
const submitForm = async () => {
  try {
   // 表单验证
   if (!formData.value.name) { ElMessage.error(t('products.devicePage.namePlaceholder')); return; }
   if (!formData.value.productId) { ElMessage.error('请选择所属产品'); return; }
   if (!formData.value.deptId) { ElMessage.error('请选择所属部门'); return; }

   // 模拟API提交
   await new Promise(resolve => setTimeout(resolve, 500));
   const response = await updateDeviceApi(formData.value.id, formData.value);
   if (response.code === 0) {
     ElMessage.success(t('products.devicePage.updateSuccess'));
     emit('update:visible', false);
     emit('success');
   } else {
     ElMessage.error(response.message || t('products.devicePage.updateFailed'));
   }
  } catch (error) {
    ElMessage.error(t('products.devicePage.updateFailed'));
    console.error('Failed to update device:', error);
  }
};

// 重置表单
const resetForm = () => {
 if (props.device) {
   formData.value = { ...props.device };
 }
};

// 关闭弹框
const closeDialog = () => { emit('update:visible', false); emit('close'); };

let productOpenStatusOptions = ref([])
onMounted(async () => {
  productOpenStatusOptions.value = await getProductOpenStatusOptions()
})

const handleImgChange = (e:any)=> {
  console.log(e)
  formData.value.image = e
}
</script>

<template>
 <el-dialog
   v-model="dialogVisible"
   :title="t('products.devicePage.edit')"
   :draggable="true"
   @close="closeDialog"
   width="700px"
 >
   <el-form
     :model="formData"
     label-width="120px"
     style="max-width: 650px; margin: 0 auto;"
   >
     <el-row :gutter="20">
       <el-col :span="12">
         <el-form-item :label="'ID'" prop="id">
           <el-input v-model="formData.id" disabled />
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.deviceNo')" prop="deviceNo">
           <el-input v-model="formData.deviceNo" disabled :placeholder="t('products.devicePage.deviceNoNotEditable')" />
         </el-form-item>
       </el-col>
     </el-row>

     <el-row :gutter="20">
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.name')" prop="name" required>
           <el-input v-model="formData.name" :placeholder="t('products.devicePage.namePlaceholder')" />
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.channelNo')" prop="channelNo">
           <el-input v-model="formData.channelNo" :placeholder="t('products.devicePage.channelNo')" />
         </el-form-item>
       </el-col>
     </el-row>

     <el-row :gutter="20">
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.productId')" prop="productId" required>
           <el-select v-model="formData.productId" :placeholder="t('products.devicePage.productId')">
             <el-option v-for="opt in productOptions" :key="opt.val" :label="opt.label" :value="opt.val" />
           </el-select>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.deptId')" prop="deptId">
           <el-cascader
             v-model="formData.deptId"
             class="w-full"
             :options="deptTreeList"
             :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
             clearable
             filterable
             :placeholder="t('products.devicePage.deptId')"
           >
             <template #default="{ node, data }">
               <span>{{ data.name }}</span>
               <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
             </template>
           </el-cascader>
         </el-form-item>
       </el-col>
     </el-row>

     <el-row :gutter="20">
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.groupId')" prop="groupId">
           <el-cascader
             v-model="formData.groupId"
             class="w-full"
             :options="deviceGroupOptions"
             :props="{
              value: 'id',
              label: 'name',
              emitPath: false,
              checkStrictly: true
            }"
             clearable
             filterable
             :placeholder="t('products.devicePage.groupId')"
           >
             <template #default="{ node, data }">
               <span>{{ data.name }}</span>
               <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
             </template>
           </el-cascader>
         </el-form-item>
       </el-col>
     </el-row>

     <el-row :gutter="20">
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.lng')" prop="lng">
           <el-input v-model.number="formData.lng" :placeholder="t('products.devicePage.lngPlaceholder')" type="number" step="0.00000001" />
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.lat')" prop="lat">
           <el-input v-model.number="formData.lat" :placeholder="t('products.devicePage.latPlaceholder')" type="number" step="0.00000001" />
         </el-form-item>
       </el-col>
     </el-row>

     <el-form-item :label="t('products.devicePage.address')" prop="address">
       <el-input v-model="formData.address" :placeholder="t('products.devicePage.addressPlaceholder')" />
     </el-form-item>

     <el-form-item :label="t('products.devicePage.image')" prop="image" required>
       <upload-img v-model:imgUrl="formData.image" @change="handleImgChange" />
       <div class="upload-hint">{{ t('products.devicePage.uploadImgHint') }}</div>
     </el-form-item>

     <el-row :gutter="20">
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.openStatus')" prop="openStatus">
           <el-select v-model="formData.openStatus" placeholder="">
             <el-option :label="t('products.devicePage.notActivated')" :value="0"></el-option>
             <el-option :label="t('products.devicePage.activated')" :value="1"></el-option>
           </el-select>
         </el-form-item>
       </el-col>
     </el-row>

     <el-row :gutter="20">
       <el-col :span="12">
         <el-form-item :label="t('products.productPage.deviceType')" prop="type" required>
           <el-select v-model="formData.type" :placeholder="t('products.productPage.selectDeviceType')">
             <el-option
               v-for="option in deviceTypeOptions"
               :key="option.val"
               :label="option.label"
               :value="option.val"
             />
           </el-select>
         </el-form-item>
       </el-col>
       <el-col :span="12" v-if="formData.type == 2">
         <el-form-item v-if="formData.type == 2" :label="t('products.devicePage.parentDevice')" prop="parentId">
           <el-select v-model.number="formData.parentId" :placeholder="t('products.devicePage.selectParentDevice')" clearable>
             <el-option
               v-for="option in parentDeviceList"
               :key="option.val"
               :label="option.label"
               :value="option.val"
             ></el-option>
           </el-select>
         </el-form-item>
       </el-col>
     </el-row>

     <el-form-item :label="t('products.devicePage.remark')" prop="remark">
       <el-input v-model="formData.remark" type="textarea" :placeholder="t('products.devicePage.remarkPlaceholder')" />
     </el-form-item>
     <el-row :gutter="20">
       <el-col :span="12">
         <el-form-item :label="t('products.devicePage.networkType')" prop="networkType">
           <el-select v-model="formData.networkType" :placeholder="t('products.devicePage.networkType')">
             <el-option :label="o.label" :value="o.val" v-for="(o,i) in networkTypeOptions" :key="i"></el-option>
           </el-select>
         </el-form-item>
       </el-col>
     </el-row>
   </el-form>

   <template #footer>
     <span class="dialog-footer">
       <el-button @click="resetForm">{{ t('buttons.reset') }}</el-button>
         <el-button type="primary" @click="submitForm">{{ t('buttons.submit') }}</el-button>
     </span>
   </template>
 </el-dialog>
</template>

<style scoped lang="scss">
.dialog-footer {
 display: flex;
 justify-content: flex-end;
 gap: 10px;
}
</style>
